import { type SendInfoWrap, type MessageWrap } from '@/apis/im'
class MyWebSocket {
  ws: any
  wsUrl: any
  // socket状态
  wsStatuc: boolean
  // 回调函数
  callBack: any
  // 心跳
  wsTimeOut: any
  // 重连
  lockReconnect: boolean

  constructor() {
    this.ws = null
    this.wsStatuc = false
    this.lockReconnect = false
  }

  initSocket(url, call) {
    if (this.wsStatuc) {
      return
    }
    this.wsStatuc = true
    this.wsUrl = url
    this.callBack = call
    this.callBack({ type: 'wsStatus', data: 'loading' })
    this.ws = uni.connectSocket({
      url,
      header: {
        'content-type': 'application/json'
      },
      success(res) {
        console.log('成功', res)
      }
    })
    this.ws.onOpen((res) => {
      console.log('webSocket已连接', res)
      this.socketOut()
      this.callBack({ type: 'wsStatus', data: 'open' })
    })
    this.ws.onClose((res) => {
      console.log('webSocket已关闭', res)
      this.reconnectWs()
      clearInterval(this.wsTimeOut)
      this.callBack({ type: 'wsStatus', data: 'close' })
    })
    this.ws.onError((res) => {
      console.log('webSocket连接错误', res)
      this.reconnectWs()
      clearInterval(this.wsTimeOut)
      this.callBack({ type: 'wsStatus', data: 'error' })
    })
    this.ws.onMessage((event) => {
      const data: SendInfoWrap = JSON.parse(event.data)
      console.log('onMessage', data)
      if (data.code === 'online') {
        this.callBack({ type: 'online', data })
      } else if (data.code === 'offline') {
        this.callBack({ type: 'offline', data })
      } else if (data.code === 'release') {
        this.callBack({ type: 'jiedan', data })
      } else {
        if (data.message) {
          this.callBack({ type: 'message', data })
        }
      }
    })
  }

  // 心跳检测
  socketOut() {
    this.wsTimeOut = setInterval(() => {
      const query = JSON.stringify({ code: 'ping' })
      // console.log('send', query)
      this.sendMsg(query)
    }, 30000)
  }

  // 重新连接
  reconnectWs() {
    if (!this.wsStatuc) {
      return
    }
    if (!this.lockReconnect) {
      this.lockReconnect = true
      setTimeout(() => {
        console.log('webSocket重新连接中')
        this.initSocket(this.wsUrl, this.callBack)
        this.lockReconnect = false
      }, 3000)
    }
  }

  // 发送数据
  sendMsg(msg) {
    console.log('send', msg)
    this.ws?.send({ data: msg })
  }

  // 关闭连接
  closeWs() {
    this.wsStatuc = false
    this.ws?.close({
      success: () => {
        console.info('退出成功')
      }
    })
  }
}
// export default {
//   initSocket,
//   sendMsg,
//   closeWs
// }

export default MyWebSocket
